package cn.stylefeng.guns.sys.modular.downloadFile.controller;

import cn.stylefeng.guns.sys.modular.downloadFile.entity.FileTable;
import cn.stylefeng.guns.sys.modular.downloadFile.service.DownloadServicce;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


import static sun.net.www.protocol.http.HttpURLConnection.userAgent;

@RestController
@RequestMapping("/data")
public class FileDownloadController {
    @Value("${web.download-path-windows}")
    private String downloadPathWindows;
    @Value("${web.download-path-linux}")
    private String downloadPathLinux;
    @Autowired
    private DownloadServicce downloadServicce;

    /*
     * 文件下载接口
     */
    @GetMapping("/downloadFile")
    public void downloadFile(Integer id, HttpServletResponse response) throws IOException {
        FileTable fileTable = this.downloadServicce.selectFileTableInfo(id);
        String filePath = fileTable.getFilePath();
        String file_name = fileTable.getFileName();
        //判断是否为Windows系统
        boolean isWindows = System.getProperty("os.name").toLowerCase().contains("windows");
        InputStream inStream = null;
        if (isWindows) {
            inStream = new FileInputStream(downloadPathWindows + filePath);
        } else {
            inStream = new FileInputStream(downloadPathLinux + filePath);
        }
        response.reset();
        if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
            file_name = java.net.URLEncoder.encode(file_name, "UTF-8");
        } else {
            // 非IE浏览器的处理：  
            file_name = new String(file_name.getBytes("UTF-8"), "ISO-8859-1");
        }
        response.setCharacterEncoding("UTF-8");
        response.setContentType("bin");
        response.addHeader("Content-Disposition", "attachment; filename=\"" + file_name + "\"");
        OutputStream outputStream = response.getOutputStream();
        byte[] bytes = new byte[1024];
        while (0 != IOUtils.read(inStream, bytes)) {
            IOUtils.write(bytes, outputStream);
        }
        IOUtils.closeQuietly(outputStream);
    }
}
